<template>
    <div id="app">
        <!--header-->
        <Header title="购物车案例"></Header>
        <div style="height: 23px;"></div>
        <!--循环渲染所有商品-->
        <Goods v-for="item in list" :key="item.id"
               :title="item.name"
               :desc="item.desc"
               :price="item.price"
               :id="item.id"
               :state="item.state"
               :count="item.count"
               @updateState="updateState"
        >
            <!--这里的$event代表着默认传的参数，也就是val-->
            <Count :count="item.count" @addCount="addCount(item,$event)"></Count>
        </Goods>
        <!--footer-->
        <Footer
                :checkAll="fullState"
                :sumPrice="sumPrice"
                :count="getCount"
                @changeAll="changeAll"
        ></Footer>
    </div>
</template>

<script>
    import axios from 'axios';
    import Header from '@/components/Header/Header.vue';
    import Goods from '@/components/Goods/Goods.vue';
    import Footer from '@/components/Footer/Footer.vue';
    import Count from '@/components/Counter/Counter.vue';

    export default {
        name: 'App',
        data(){
            return {
                list:[]
            }
        },
        methods:{
            async searchList(){
                const {data:res} = await axios.get('http://localhost:9000/queryListChat');
                if (res.code === '0') {
                    this.list = res.list;
                }
            },
            updateState(id,changedState){
                this.list.some(item=>{
                    if (item.id === id) {
                        item.state = changedState
                        return true;
                    }
                })
            },
            changeAll(val){
                this.list.forEach(item=>item.state=val);
            },
            addCount(item,val){
                item.count+=val;
            }
        },
        computed:{
            fullState(){
                return this.list.every(item=>item.state);
            },
            sumPrice(){
                return this.list.filter(item=>item.state).reduce((sum,item)=>{
                    return sum+item.price*item.count;
                },0)
            },
            getCount(){
                return this.list.filter(item=>item.state).reduce((sum,item)=>{
                    return sum+item.count;
                },0);
            }
        },
        components: {
            Header,Goods,Footer,Count
        },
        created() {
            this.searchList();
        }
    }
</script>

<style lang="less">
    #app {
        font-family: Avenir, Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        color: #2c3e50;
    }
</style>
